const Router = require('koa-router')
const { Customer, Order } = require('../models')
const auth = require('../middleware/auth')
const { Op } = require('sequelize')

const router = new Router({ prefix: '/api' })

// 获取客户列表
router.get('/customers', auth.requirePermission('customer:read'), async (ctx) => {
  try {
    const {
      page = 1,
      size = 10,
      search = '',
      type,
      status,
      sort = 'created_at',
      order = 'DESC'
    } = ctx.query

    const offset = (page - 1) * size
    const where = {}

    // 搜索条件
    if (search) {
      where[Op.or] = [
        { name: { [Op.like]: `%${search}%` } },
        { code: { [Op.like]: `%${search}%` } },
        { contact_person: { [Op.like]: `%${search}%` } },
        { phone: { [Op.like]: `%${search}%` } },
        { email: { [Op.like]: `%${search}%` } }
      ]
    }

    if (type) {
      where.type = type
    }

    if (status !== undefined) {
      where.status = status
    }

    const { count, rows } = await Customer.findAndCountAll({
      where,
      include: [
        {
          model: Order,
          as: 'orders',
          attributes: ['id', 'total_amount', 'status'],
          required: false
        }
      ],
      order: [[sort, order.toUpperCase()]],
      limit: parseInt(size),
      offset
    })

    // 添加统计信息
    const customersWithStats = rows.map(customer => {
      const orders = customer.orders || []
      return {
        ...customer.toJSON(),
        order_count: orders.length,
        total_amount: orders.reduce((sum, order) => sum + parseFloat(order.total_amount || 0), 0)
      }
    })

    ctx.body = {
      code: 200,
      message: '获取客户列表成功',
      data: {
        list: customersWithStats,
        total: count,
        page: parseInt(page),
        size: parseInt(size)
      }
    }
  } catch (error) {
    console.error('获取客户列表失败:', error)
    ctx.body = {
      code: 500,
      message: '获取客户列表失败',
      error: error.message
    }
  }
})

// 获取客户详情
router.get('/customers/:id', auth.requirePermission('customer:read'), async (ctx) => {
  try {
    const { id } = ctx.params

    const customer = await Customer.findByPk(id, {
      include: [
        {
          model: Order,
          as: 'orders',
          attributes: ['id', 'order_no', 'total_amount', 'status', 'created_at'],
          limit: 10,
          order: [['created_at', 'DESC']]
        }
      ]
    })

    if (!customer) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '客户不存在'
      }
      return
    }

    ctx.body = {
      code: 200,
      message: '获取客户详情成功',
      data: customer
    }
  } catch (error) {
    console.error('获取客户详情失败:', error)
    ctx.body = {
      code: 500,
      message: '获取客户详情失败',
      error: error.message
    }
  }
})

// 创建客户
router.post('/customers', auth.requirePermission('customer:create'), async (ctx) => {
  try {
    const {
      name,
      code,
      type = 'individual',
      contact_person,
      phone,
      email,
      address,
      credit_limit,
      tax_id,
      bank_account,
      description,
      status = 1
    } = ctx.request.body

    // 验证必填字段
    if (!name || !contact_person || !phone) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '客户名称、联系人和联系电话为必填项'
      }
      return
    }

    // 检查编码是否已存在
    if (code) {
      const existingCode = await Customer.findOne({ where: { code } })
      if (existingCode) {
        ctx.status = 400
        ctx.body = {
          code: 400,
          message: '客户编码已存在'
        }
        return
      }
    }

    const customer = await Customer.create({
      name,
      code,
      type,
      contact_person,
      phone,
      email,
      address,
      credit_limit: parseFloat(credit_limit) || 0,
      tax_id,
      bank_account,
      description,
      status
    })

    ctx.body = {
      code: 200,
      message: '创建客户成功',
      data: customer
    }
  } catch (error) {
    console.error('创建客户失败:', error)
    ctx.body = {
      code: 500,
      message: '创建客户失败',
      error: error.message
    }
  }
})

// 更新客户
// 更新客户
router.put('/customers/:id', auth.requirePermission('customer:update'), async (ctx) => {
  try {
    const { id } = ctx.params
    const {
      name,
      code,
      type,
      contact_person,
      phone,
      email,
      address,
      credit_limit,
      tax_id,
      bank_account,
      description,
      status
    } = ctx.request.body

    const customer = await Customer.findByPk(id)
    if (!customer) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '客户不存在'
      }
      return
    }

    // 如果更新编码，检查新编码是否已存在
    if (code && code !== customer.code) {
      const existingCode = await Customer.findOne({ where: { code } })
      if (existingCode) {
        ctx.status = 400
        ctx.body = {
          code: 400,
          message: '客户编码已存在'
        }
        return
      }
    }

    const updateData = {}
    if (name !== undefined) updateData.name = name
    if (code !== undefined) updateData.code = code
    if (type !== undefined) updateData.type = type
    if (contact_person !== undefined) updateData.contact_person = contact_person
    if (phone !== undefined) updateData.phone = phone
    if (email !== undefined) updateData.email = email
    if (address !== undefined) updateData.address = address
    if (credit_limit !== undefined) updateData.credit_limit = parseFloat(credit_limit)
    if (tax_id !== undefined) updateData.tax_id = tax_id
    if (bank_account !== undefined) updateData.bank_account = bank_account
    if (description !== undefined) updateData.description = description
    if (status !== undefined) updateData.status = status

    await customer.update(updateData)

    ctx.body = {
      code: 200,
      message: '更新客户成功',
      data: customer
    }
  } catch (error) {
    console.error('更新客户失败:', error)
    ctx.body = {
      code: 500,
      message: '更新客户失败',
      error: error.message
    }
  }
})

// 删除客户
// 删除客户
router.delete('/customers/:id', auth.requirePermission('customer:delete'), async (ctx) => {
  try {
    const { id } = ctx.params

    const customer = await Customer.findByPk(id)
    if (!customer) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '客户不存在'
      }
      return
    }

    // 检查是否有关联的订单
    const orderCount = await Order.count({ where: { customer_id: id } })
    if (orderCount > 0) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '该客户还有关联的订单，无法删除'
      }
      return
    }

    await customer.destroy()

    ctx.body = {
      code: 200,
      message: '删除客户成功'
    }
  } catch (error) {
    console.error('删除客户失败:', error)
    ctx.body = {
      code: 500,
      message: '删除客户失败',
      error: error.message
    }
  }
})

// 获取客户统计信息
router.get('/:id/stats', auth.requirePermission('customer:read'), async (ctx) => {
  try {
    const { id } = ctx.params

    const customer = await Customer.findByPk(id)
    if (!customer) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '客户不存在'
      }
      return
    }

    // 统计订单信息
    const orders = await Order.findAll({
      where: { customer_id: id },
      attributes: ['id', 'total_amount', 'status', 'created_at']
    })

    const stats = {
      total_orders: orders.length,
      total_amount: orders.reduce((sum, order) => sum + parseFloat(order.total_amount || 0), 0),
      pending_orders: orders.filter(order => order.status === 'pending').length,
      completed_orders: orders.filter(order => order.status === 'completed').length,
      cancelled_orders: orders.filter(order => order.status === 'cancelled').length
    }

    ctx.body = {
      code: 200,
      message: '获取客户统计信息成功',
      data: stats
    }
  } catch (error) {
    console.error('获取客户统计信息失败:', error)
    ctx.body = {
      code: 500,
      message: '获取客户统计信息失败',
      error: error.message
    }
  }
})

module.exports = router